#include "comm.hpp"

int main(){
    
    log("Child pid is : ", Debug) << getpid() << endl;
    // 创建 key
    key_t k = ftok(PHATNAME, PROJ_ID);
    if( k == -1){
        log("Create key failed! ", Error) << " Client : " << k << endl;
        exit(1);
    }
    log("Create key done! ", Debug) << " Client : " << k << endl;

    int shmid = shmget(k, SHM_SIZE, 0);
    if(shmid == -1){
        log("Create shmid failed! ", Error) << " Client shmid : " << k << endl;
        exit(2);
    }

    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == nullptr){
        log("Detach shmid failed! ", Error) << " Client shmid : " << k << endl;
        exit(2);
    }
    log("Detach shmid done! ", Debug) << " Client shmid : " << k << endl;

    // 使用共享内存：实现通信
    // 直接使用共享内存实现通信（不加以控制）
#if 0
    char a = 'a';
    for(;a<='e';a++){
        // 每次都想 shmaddr（共享内存的起始地址起）写入数据！
        snprintf(shmaddr, SHM_SIZE-1, 
            "Hello server: 我是其他进程：我的 pid：%d，inc：%c\n",getpid(), a);
        sleep(2);
    }

    strcpy(shmaddr, "quit");
#endif

    // （实验）混合系统调用方式实现通信
#if 0
    while(true){
        ssize_t s = read(0, shmaddr, SHM_SIZE-1);
        if(s>0){
            shmaddr[s-1] = 0;
            if(strcmp(shmaddr, "quit") == 0) break;
        }
    }
#endif

    // 结合管道，实现共享内存级的进程通信控制
#if 1
    int fd = OpenFIFO(FIFO_NAME, WRITE);
    // 使用
    // client将共享内存看做一个char 类型的buffer
    while(true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE-1);
        if(s > 0)   // 有数据就唤醒读取
        {
            shmaddr[s-1] = 0;
            Signal(fd);
            if(strcmp(shmaddr,"quit") == 0) break;
        }
    }

    CloseFifo(fd);
#endif

    // 去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    log("Ndetach shmid done! ", Debug) << " Client shmid : " << k << endl;


    // 客户端不需要删除共享内存【由服务端执行】

    return 0;
}